Skip to content

homework-tk - #14

Open
tatiana-kornienko14 wants to merge 20 commits into
DafeMipt212:mainfrom
tatiana-kornienko14:main
Open

homework-tk#14
tatiana-kornienko14 wants to merge 20 commits into
DafeMipt212:mainfrom
tatiana-kornienko14:main

Conversation

@tatiana-kornienko14

Copy link
Copy Markdown

No description provided.

@tatiana-kornienko14 tatiana-kornienko14 changed the title дз Корниенко homework-tk Dec 12, 2022
Comment thread homework_01/task_01/src/utils.cpp Outdated

std::vector<std::string> SplitString(const std::string& data) {
return {};
std::vector<std::string> v;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

плохое имя у переменной, непонятно что она означает

Comment thread homework_01/task_01/src/utils.cpp Outdated
std::vector<std::string> v;
std::string tmp = "";

for (auto c : s) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут ошибка компиляции будет, нет переменной s

Comment thread homework_01/task_01/src/utils.cpp Outdated
std::string tmp = "";

for (auto c : s) {
if (c != ' ') {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если посмотреть в тесты, то там не только по пробелу разделение идет, но и по символу табуляции ('\t')

Comment thread homework_01/task_02/src/utils.cpp Outdated
Comment thread homework_01/task_02/src/utils.cpp Outdated

#include <regex>
#include <stack>
#define vector_string std::vector<std::string>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using vector_string = std::vector<std::string>;

так же можно использовать typedef

не стоит использовать define где этого можно избежать

Comment thread homework_01/task_02/src/utils.cpp Outdated

int Calculate(const std::string& data) {
return 0;
std::vector<int> v1; // хотела сделать тип double, но в тестах int, так что пока так

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если хочешь сделай double, это только плюс

название переменной так себе (непонятно что означает)

Comment thread homework_01/task_02/src/utils.cpp Outdated
return 0;
std::vector<int> v1; // хотела сделать тип double, но в тестах int, так что пока так
std::string tmp;
bool f = 0, pr = 0, dl = 0, mns = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

совсем непонятные названия переменных, и хорошая практика: одна переменная - одна строка

Comment thread homework_01/task_02/src/utils.cpp Outdated
bool f = 0, pr = 0, dl = 0, mns = 0;

for (size_t i = 0; i < data.size(); ++i) {
if (data[i] != "*" && data[i] != "+" && data[i] != "-" && data[i] != "/" && !(is_numb(data[i]))) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

!(is_numb(data[i])) лишние круглые скобки

а ещё лучше вот так оформить:

  if (data[i] != "*" &&
      data[i] != "+" &&
      data[i] != "-" &&
      data[i] != "/" &&
      !is_numb(data[i]))

Comment thread homework_01/task_02/src/utils.cpp Outdated

for (size_t i = 0; i < data.size(); ++i) {
if (data[i] != "*" && data[i] != "+" && data[i] != "-" && data[i] != "/" && !(is_numb(data[i]))) {
std::cout << "ошибка!\n";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут можно кинуть исключение, например std::runtime_error

@LostPointer

Copy link
Copy Markdown
Contributor

в первой задаче не рассмотрен случай со скобками и табуляцией

Comment thread homework_01/task_02/src/utils.cpp Outdated
#include <stack>
#define vector_string std::vector<std::string>

bool is_numb(const std::string &str) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В большинстве случаев не стоит сокращать слова в именах. Имя IsNumber (ну или is_number) проще понять, чем is_numb (к тому же numb переводится с английского как онемевший, что добавляет двусмысленности)

Comment thread homework_01/task_02/src/utils.cpp Outdated
bool f = 0, pr = 0, dl = 0, mns = 0;

for (size_t i = 0; i < data.size(); ++i) {
if (data[i] != "*" && data[i] != "+" && data[i] != "-" && data[i] != "/" && !(is_numb(data[i]))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Следующий код не скомпилируется
if (data[i] != "*" && data[i] != "+" && data[i] != "-" && data[i] != "/" && !(is_numb(data[i]))).
Первая причина: data[i] имеет тип char, а символы "*", "+", "-" и "/" тип const char*, и сравнивать их нельзя.
Вторая причина: функция is_numb принимает аргумент типа const std::string &str, а вы передаёте char.
Можно исправить эту строчку так:
if (data[i] != '*' && data[i] != '+' && data[i] != '-' && data[i] != '/' && !(is_numb(std::to_string(data[i]))))

Comment thread homework_01/task_02/src/utils.cpp Outdated
}

if (f) {
if (data[i] == ")") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не скомпилируется. Исправление: data[i] == ')'

Comment thread homework_01/task_02/src/utils.cpp Outdated
continue;
}

if (data[i] == "(") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data[i] == '('

Comment thread homework_01/task_02/src/utils.cpp Outdated
}

if (pr) {
v1[v1.size()-1] *= std::stoi(data[i]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не скомпилируется. Функция std::stoi принимает строку, не char. Вариант исправления:

v1[v1.size() - 1] *= data[i] - '0';

Comment thread homework_01/task_02/src/utils.cpp Outdated
continue;
}

if (data[i] == "*") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data[i] == '*'

Comment thread homework_01/task_02/src/utils.cpp Outdated
continue;
}

if (data[i] == "/") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data[i] == '/'

Comment thread homework_01/task_02/src/utils.cpp Outdated
continue;
}

if (data[i] == "-") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data[i] == '-'

Comment thread homework_01/task_02/src/utils.cpp Outdated
continue;
}

if (data[i] == "+") {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

data[i] == '+'

Comment thread homework_01/task_02/src/utils.cpp Outdated
continue;
}

v1.push_back(std::stoi(data[i]));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

v1.push_back(data[i] - '0');

tatiana-kornienko14 and others added 11 commits December 13, 2022 05:32
поправила названия переменных, добавила проверку на табуляцию
я так посмотрела, define у меня в принципе нигде не используется... упс
увидела, кстати, у себя заметную проблему в коде, скоро исправлю, заодно доисправляю названия переменных

@LostPointer LostPointer left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

поправь в тестах для первого задания с { "a", "(a a)", "b", "(asd as)" } на { "a", "a a", "b", "asd as" }, так будут проходить тесты

Comment thread homework_01/task_01/src/utils.cpp Outdated
is_bracket = 0;
if (tmp != "") {
answer.push_back(tmp);
tmp = "";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше оспользовать метод clear: tmp.clear()
это даст немного больше понимания что ты очищаешь переменную, а не присваиваешь значение переменной

Comment thread homework_01/task_02/src/utils.cpp Outdated
#include <iostream>
#include <regex>
#include <stack>
#include "utils.hpp"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а вот если у тебя два файла с одинаковым мененм и расширениями .cpp и .hpp, в cpp инклуд hpp должен идти первым. получится примерно вот так:

#include "utils.hpp"

#include <regex>
#include <stack>
#include <iostream>

Comment thread homework_01/task_02/src/utils.cpp Outdated
}

if (!is_number(number)) {
throw ("ошибка!\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread homework_01/task_02/src/utils.cpp Outdated
}

if (multipl) {
terms[terms.size()-1] *= std::stoi(number);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пробелы пропущены: terms.size() - 1

number += data[i];
continue;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Скобочки у вас пока ещё корректно не обрабатываются. Наличие скобочек приводит к вылетам программы. Чтобы исправить вылеты, вставьте сюда код (но это ещё не всё):

if (number.empty())
  continue;

minus = 0;
} else {
terms.push_back(std::stoi(number));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чтобы исправить вылеты из-за скобочек, окружите операторы if-else ещё одной проверкой:

if (!number.empty())
{
    if (multipl) {
        terms[terms.size() - 1] *= std::stoi(number);
        multipl = 0;
    } else if (division) {
        terms[terms.size() - 1] /= std::stoi(number);
        division = 0;
    } else if (minus) {
        terms.push_back(-std::stoi(number));
        minus = 0;
    } else {
        terms.push_back(std::stoi(number));
    }
}


for (size_t i = 0; i < data.size(); ++i) {
if (is_brackets) {
if (data[i] == ')') {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Замечу просто, что если отключать флаг is_brackets сразу, как только встречается закрывающая скобка, то вложенные друг в друга скобки точно корректно оброватываться не будут. Впрочем, для первого задания и так хорошо

Comment thread homework_01/task_02/src/utils.cpp Outdated
}

if (multipl) {
terms[terms.size() - 1] *= std::stoi(number);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::stoi(number) возвращает int, а term хранит double (да и функция Calculate, вроде, должна double возвращать). Нестыковка)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants